<template>
  <el-dialog
      v-model="visible"
      :title="(form.id) ? '编辑列表' : '新建列表'"
      width="400px"
      :before-close="handleClose"
  >
    <el-form 
      :model="form" 
      label-width="80px"
      :rules="rules"
      ref="formRef"
    >
      <el-form-item label="列表名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button 
        type="primary" 
        @click="submitForm"
        :loading="submitting"
      >
        确认
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useListStore } from '@/store/list'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: Boolean,
  list: {
    type: Object,
    default: () => ({ name: '' })
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const listStore = useListStore()
const visible = ref(false)
const formRef = ref(null)
const submitting = ref(false)
const form = ref({ 
  id: null,
  name: '' 
})

const rules = {
  name: [
    { required: true, message: '请输入列表名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在1到20个字符', trigger: 'blur' }
  ]
}

watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    form.value = props.list.id 
      ? { ...props.list } 
      : { id: null, name: '' }
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

const handleClose = () => {
  formRef.value?.resetFields()
  visible.value = false
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (form.value.id) {
      await listStore.updateList(form.value.id, form.value)
      ElMessage.success('列表更新成功')
    } else {
      await listStore.createList(form.value)
      ElMessage.success('列表创建成功')
    }
    
    emit('success')
    handleClose()
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error(error.message || '操作失败')
    }
  } finally {
    submitting.value = false
  }
}
</script>